package com.sixmac.platform.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.sixmac.core.base.service.BaseService;
import com.sixmac.core.constant.ConstCache;
import com.sixmac.core.constant.ConstCacheKey;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.cache.CacheKit;
import com.sixmac.core.toolbox.kit.DateKit;
import com.sixmac.core.toolbox.kit.JsonKit;
import com.sixmac.module.*;
import com.sixmac.platform.service.IndexService;
import com.sixmac.util.Push;
import com.sixmac.util.WeChatConfig;
import com.sixmac.utils.HttpRequestUtil;
import com.sixmac.utils.LockManage;
import com.sixmac.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * Created by admin on 2018/9/4.
 */
@Service
public class IndexServiceImpl extends BaseService<Tenant> implements IndexService {

    @Autowired
    WeChatConfig weChatConfig;

    public AjaxResult applyKey(Tenant tenant,String lockNo) {
        AjaxResult res = new AjaxResult();
        tenant = this.findById(tenant.getId());

        Room room = Blade.create(Room.class).findFirstBy(" lockNo='"+lockNo+"'",null);

        if (room==null){
            return error("当前锁未安装！");
        }

        res.setData(room);

        //判断用户是否完善资料
        if (Strings.isNullOrEmpty(tenant.getMobile()) || Strings.isNullOrEmpty(tenant.getIdCard())) {
            return error("用户未完善资料！");
        }

        return res.setCode(0);
    }

    @Transactional
    public AjaxResult doApplyKey(Tenant tenant, String roomNo,String form_id, String contract) {
        Room room = Blade.create(Room.class).findFirstBy("lockNo=#{roomNo}", getData("roomNo", roomNo));
        tenant = Blade.create(Tenant.class).findById(tenant.getId());
        if (room == null)
            return error("房屋找不到");

        if (Blade.create(TenantRoom.class).findFirstBy("tenantId = #{tenantId} and status = 1", getData("tenantId", tenant.getId())) != null)
            return error("该用户已经入住。");


        TenantRoom tenantRoom = new TenantRoom();
        tenantRoom.setTenantId(tenant.getId());
        tenantRoom.setRoomId(room.getId());
        String[] contracts = contract.split(",");
        for (int i = 0;i<contracts.length;i++){
            if (i == 0){
                tenantRoom.setContract(contracts[i]);
            }
            if (i == 1){
                tenantRoom.setContract2(contracts[i]);
            }
            if (i == 2){
                tenantRoom.setContract3(contracts[i]);
            }
        }

        tenantRoom.setLandlordId(room.getLandlordId());
        tenantRoom.setCreateDate(new Date());
        tenantRoom.setApprove(3);
        tenantRoom.setKey(room.getKey() == null ? "" : room.getKey());
        Blade.create(TenantRoom.class).save(tenantRoom);

        AccessFrom accessFrom = new AccessFrom();
        accessFrom.setCreatTime(new Date());
        accessFrom.setIsUse(0);
        accessFrom.setFormId(form_id);
        accessFrom.setType(1);
        accessFrom.setUserId(tenant.getId());
        Blade.create(AccessFrom.class).save(accessFrom);

        return success("申请成功");
    }

    @Transactional
    public AjaxResult record(Tenant tenant, String form_id) {

        Contract contract = Blade.create(Contract.class).findFirstBy(" tentantId="+tenant.getId()+" and status = 0",null);
        if (contract == null){
            return error("房间不存在");
        }

        if (new Date().getTime()<contract.getStartTime().getTime()){
            return error("不在租房时间范围内！");
        }

        if (new Date().getTime()>contract.getEndTime().getTime()){
            return error("不在租房时间范围内！");
        }

        AccessFrom accessFrom = new AccessFrom();
        accessFrom.setCreatTime(new Date());
        accessFrom.setIsUse(0);
        accessFrom.setFormId(form_id);
        accessFrom.setType(1);
        accessFrom.setUserId(tenant.getId());
        Blade.create(AccessFrom.class).save(accessFrom);

        Room room = Blade.create(Room.class).findById(contract.getRoomId());

        LockManage lockManage = new LockManage();
        LockUser lockUser = new LockUser();
        lockUser.setDeviceCode(room.getLockNo());
        lockUser.setUnlockWay("1");
        lockUser.setLockUserInfo(RandomUtil.generateMixString(16-(tenant.getId()+"").length())+""+tenant.getId());
        lockUser.setMsgId("100"+tenant.getId());
        lockUser.setLockUserType("12");
        lockUser.setStartDay(System.currentTimeMillis()/1000+"");
        lockUser.setEndDay(DateKit.parseTime(DateKit.getAfterDayDate("3")).getTime()/1000+"");
        lockUser.setUserFlag("100"+tenant.getId());
        Boolean result = lockManage.addUser(lockUser);

        if(!result){
            return error("请点亮门锁。");
        }

//        lockUser = new LockUser();
//        lockUser.setLockUserInfo("100"+tenant.getId());
//        lockUser.setDeviceCode(room.getLockNo());
//        lockUser.setMsgId("100"+tenant.getId());
//        Boolean result = lockManage.addFingerprint(lockUser);

//        if(!result){
//            return error("请点亮门锁。");
//        }

        Push push = new Push();
        push.openClock(tenant,null,contract.getRoomId(),weChatConfig);

        return success("请按锁录入指纹");
    }


    public AjaxResult cancelRoom(Tenant tenant) {
        TenantRoom tenantRoom = Blade.create(TenantRoom.class).findFirstBy("status =1  and tenantId = " + tenant.getId(), null);
        if (tenantRoom.getStatus() != 1)
            return error("状态错误");
        tenantRoom.setStatus(2);
        Tenant t = Blade.create(Tenant.class).findById(tenant.getId());
        Blade.create(Tenant.class).update(t);
        Blade.create(TenantRoom.class).update(tenantRoom);
        return success("退租成功");
    }


}
